package com.nabton.ndscollector;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.nabton.ndscollector.connection.ConnectionManager;
import com.nabton.ndscollector.connection.RequestInterface;
import com.nabton.ndscollector.database.DatabaseManager;
import com.nabton.ndscollector.values.NabControl;
import com.nabton.ndscollector.values.NabEntry;
import com.nabton.ndscollector.values.NabStatus;


public class NDSCollector implements RequestInterface{
    public static DatabaseManager dbManagerData;
    public static DatabaseManager dbManagerControl;
    
    public static ConnectionManager connManager;
    public static NDSCollector server;
    public static Scanner userInput;
    
    public static void main(String [] args)
    {
        server   = new NDSCollector();
        dbManagerData   = new DatabaseManager();
        dbManagerControl= new DatabaseManager();
        connManager = new ConnectionManager(7643, "127.0.0.1", server);
        userInput = new Scanner(System.in);

        System.out.println("--NDS Collector online--");
        connManager.startServer();
        NabStatus s1 = dbManagerData.openDatabase("NDSCollection.db");
        NabStatus s2 = dbManagerControl.openDatabase("NDSControl.db");
      
        if(NabStatus.OK == s1 && NabStatus.OK == s2)
        {
        	System.out.println("#Waiting for requests...");
        }
        else
        {
            System.out.println("#Problem opening databases");
        }
        
        String cmdNabton;
        while(true)
        {
            //Request user command
            cmdNabton = userInput.next();
            
            if (cmdNabton.compareTo("quit") == 0)
            {
                break;
            }
        }        
        //Take down server
        connManager.stopServer();
        dbManagerData.closeDatabase();
        dbManagerControl.closeDatabase();
    	System.out.println("--NDS Collector shutdown complete--");
    }

    @Override
    public NabStatus handleDataRequest(NabEntry entry)
    {

        //2. Add to data to database
        dbManagerData.setupNewStream(entry.getStreamId());
        dbManagerData.addMeasurement(entry.getStreamId(),entry.getData());
        
        return NabStatus.OK;
    }
    
    @Override
    public NabStatus verifyStreamId(int sid)
    {
        //Check if sid is valid TODO
        return NabStatus.OK;
    }
    
    @Override
    public List<NabControl> fetchControlMessage(int sid)
    {
        //Check if sid is valid
        return dbManagerControl.fetchControlMessage(sid);
    }
    
    
    
    
}

